<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{courseForm.courseTitle!=null&&courseForm.courseTitle!=''?courseForm.courseTitle:"正在加载"}}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-row>
      <div style="height: 20px;"></div>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="17">
        <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
          :options="playerOptions" @play="onPlayerPlay($event)" @pause="onPlayerPause($event)"
          @ended="onPlayerEnded($event)" @timeupdate="onPlayerTimeupdate($event)" v-if="videoFiles.length>0">

          <!-- <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
          :options="playerOptions" @ready="playerReadied" @play="onPlayerPlay($event)" @pause="onPlayerPause($event)"
          @ended="onPlayerEnded($event)" @timeupdate="onPlayerTimeupdate($event)" v-if="videoFiles.length>0"> -->
        </video-player>
      </el-col>
      <el-col :span="7">
        <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
          <el-tab-pane label="简介" name="first">
            {{courseForm.courseDes!=null&&courseForm.courseDes!=''?courseForm.courseTitle:"简介"}}</el-tab-pane>
          <el-tab-pane label="目录" name="second">
            <el-table :data="videoFiles" :cell-class-name="tableCellClassName" @cell-click="videoChange($event)"
              :show-header="false" style="width: 100%">
              <el-table-column prop="listName">
              </el-table-column>

              <!-- <el-table-column prop="id"> -->
              <!-- v-for="(item,index) in scheduleFormList" -->
              <el-table-column label="状态" :key="index">
                <template slot-scope="scope">
                  <i class="el-icon-success" v-if="videoStateIcon(scope.row.id,scope.$index)" style="color:lightgreen;">
                  </i>
                </template>
              </el-table-column>

              <!-- </el-table-column> -->

            </el-table>
          </el-tab-pane>
          <el-tab-pane label="附件" name="third">
            <el-table :data="documentFiles" :cell-class-name="documentTableCellClassName" :show-header="false"
              style="width: 100%">
              <el-table-column prop="listName">

              </el-table-column>
              <el-table-column label="下载">
                <template slot-scope="scope">

                  <el-link type="primary" target="_blank" :download="scope.row.listName" :href="scope.row.listUrl">
                    <el-button type="text">下载</el-button>
                  </el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

  </div>

</template>
<script>
  export default {
    created() {
      // this.courseForm.id = this.$route.params.id
      this.courseForm.id = this.$route.query.courseId
      this.getdata()
    },
    data() {
      return {
        // 计时
        timer: '',
        gklog: '', //视频观看时长
        playerOptions: {
          playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
          autoplay: true, //如果true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 导致视频一结束就重新开始。
          muted: false, // 默认情况下将会消除任何音频。
          preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: 'zh-CN',
          aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          flash: {
            hls: {
              withCredentials: false
            }
          },
          html5: {
            hls: {
              withCredentials: false
            }
          },
          sources: [{
            id: '',
            type: '',
            src: 'http://r7oxru06n.hn-bkt.clouddn.com/c110b96a121b459dbd770ebbe4c12643-20220314111750.mp4' //url地址
          }],
          poster: '../../static/images/test.jpg', //你的封面地址
          // width: document.documentElement.clientWidth,
          notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true,
            durationDisplay: true,
            remainingTimeDisplay: true,
            fullscreenToggle: true //全屏按钮
          }
        },

        // modules: {},
        gklog: '', //视频观看时长
        activeName: 'first', //  选项卡
        courseForm: {
          // 课程id
          id: '',
          // 课程标题
          courseTitle: '',
          // 课程描述
          courseDes: ''
        },
        videoFiles: [{
          id: '',
          listName: '',
          listUrl: '',
          listDes: '',
          listFormat: ''
        }],
        documentFiles: [{
          id: '',
          listName: '',
          listUrl: '',
          listDes: '',
          listFormat: ''
        }],
        scheduleFormList: [],
        scheduleForm: {
          userId: '',
          courseId: '',
          listId: '',
          schedule: '',
          isAccomplish: ''
        }
      }

      // 进度条禁用
      this.$refs.videoPlayer.$el.firstChild
        .getElementsByClassName('vjs-control-bar')[0]
        .getElementsByClassName('vjs-progress-control')[0].style.pointerEvents =
        'none'
    },
    methods: {
      // 看看该不该显示
      videoStateIcon(id, index) {
        const find = this.scheduleFormList.find(item => item.listId == id)
        if (find && find.isAccomplish == 1) {
          let i = ++index
          console.log("i", i);
          return true
        }
        return false
        // console.log(this.scheduleFormList)
        // //  debugger
        // console.log('row', row)
        // console.log('item', item)

        // console.log(
        //   row.id,
        //   item.listId,
        //   item.isAccomplish,
        //   row.id == item.listId && item.isAccomplish == 1
        // )
        // if (row.id == item.listId && item.isAccomplish == 1) {
        //   return true
        // }

        // return false
      },
      // 播放回调
      onPlayerPlay(player) {
        //this.timer = setInterval(this.saveVideoSchedule(), 30000)
        console.log('player play!', player)
      },

      // 暂停回调
      onPlayerPause(player) {
        clearInterval(this.timer)
        console.log('player pause!', player)
      },

      // 视频播完回调
      onPlayerEnded($event) {
        console.log(this.$refs.videoPlayer.player)
        this.scheduleForm.isAccomplish = 1
        this.saveVideoSchedule()
      },

      /* 获取视频播放进度 */
      onPlayerTimeupdate(player) {
        // console.log(player)
        // console.log('进度', player.cache_.currentTime / player.cache_.duration)
        // this.gklog = player.cache_.currentTime
        // console.log('onPlayerTimeupdate!', this.gklog)
      },
      /* 设置视频进度 */
      playerReadied(player) {
        console.log('playerReadied()触发')
        console.log('视频的id', this.playerOptions.sources[0].id)
        this.scheduleMessage()
        console.log(this.scheduleForm)
        this.getVideoSchedule(this.scheduleForm)
        player.currentTime(this.scheduleForm.gklog)

        this.$refs.videoPlayer.player.play()
      },
      // 选项卡点击
      handleClick(tab, event) {
        // console.log(tab, event);
      },
      // 获取数据
      getdata() {
        this.userId = JSON.parse(localStorage.getItem('userdata')).id

        console.log('userId', this.userId)

        this.$axios.get('/api/course/' + this.courseForm.id).then(res => {
          if (res.data.code === 200) {
            console.log(res)
            let data = res.data.data
            this.loading = false
            // 课程页面基础数据赋值
            this.courseForm.id = data.id
            this.courseForm.courseTitle = data.courseTitle
            this.courseForm.courseDes = data.courseDes

            // 把视频数据给页面进行赋值
            this.videoFiles = []
            let arr = []
            let arr1 = []
            for (let index = 0; index < data.files.length; index++) {
              if (data.files[index].listFormat == 2) {
                let array = data.files[index].listName.split('.')

                arr[arr.length] = {
                  id: data.files[index].id,
                  //  切掉名字后面的格式如.mp4
                  listName: data.files[index].listName.substring(
                    0,
                    data.files[index].listName.length -
                    array[array.length - 1].length -
                    1
                  ),
                  listUrl: 'http://' + data.fileDomain + '/' + data.files[index].listUrl,
                  listDes: data.files[index].listDes,
                  listFormat: data.files[index].listFormat
                }
              } else if (data.files[index].listFormat == 3) {
                let array = data.files[index].listName.split('.')
                arr1[arr.length] = {
                  id: data.files[index].id,
                  //  切掉名字后面的格式如.mp4
                  // listName: data.files[index].listName.substring(
                  //   0,
                  //   data.files[index].listName.length -
                  //     array[array.length - 1].length -
                  //     1
                  // ),

                  listName: data.files[index].listName,
                  listUrl: 'http://' + data.fileDomain + '/' + data.files[index].listUrl,
                  listDes: data.files[index].listDes,
                  listFormat: data.files[index].listFormat
                }
              }
            }
            // 第一个视频的链接先赋上
            this.playerOptions.sources[0].src = arr[0].listUrl
            this.playerOptions.sources[0].id = arr[0].id
            // 用中间值接的现在赋值回去
            this.videoFiles = arr
            this.documentFiles = arr1
            this.scheduleMessage()
            this.$axios
              .post('/api/course/allSchedule', this.scheduleForm)
              .then(res => {
                if (res.data.code === 200) {
                  this.$message.success(res.data.message)
                  console.log('查询用户当前课程的所有视频进度', res.data)
                  this.scheduleFormList = res.data.data
                  // for (let i = 0; i < res.data.data.length; i++) {
                  //   console.log('res.data.data[i]', res.data.data[i])
                  //   this.scheduleFormList.push(res.data.data[i])
                  // }
                  console.log(
                    '查询用户当前课程的所有视频进度',
                    this.scheduleFormList
                  )
                }
              })
          }
        })
      },
      tableCellClassName({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        //注意这里是解构
        //利用单元格的 className 的回调方法，给行列索引赋值
        row.index = rowIndex
        column.index = columnIndex
      },
      documentTableCellClassName({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        //注意这里是解构
        //利用单元格的 className 的回调方法，给行列索引赋值
        row.index = rowIndex
        column.index = columnIndex
      },
      videoChange(column) {
        this.playerOptions.sources[0].src = this.videoFiles[column.index].listUrl
        this.playerOptions.sources[0].id = this.videoFiles[column.index].id
      },

      scheduleMessage() {
        (this.scheduleForm.userId = this.userId),
        (this.scheduleForm.courseId = this.courseForm.id),
        (this.scheduleForm.listId = this.playerOptions.sources[0].id),
        (this.scheduleForm.schedule = this.gklog),
        (this.scheduleForm.userId = this.courseForm.id)
      },
      // 查询用户课程视频进度
      getVideoSchedule(scheduleForm) {
        this.$axios.post('/api/course/schedule', this.scheduleForm).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            console.log('查询用户课程视频进度', res.data)
          }
        })
      },
      // 保存用户课程视频的进度
      saveVideoSchedule() {
        this.scheduleMessage()
        this.scheduleForm.schedule = this.$refs.videoPlayer.player.cache_.currentTime

        if (this.scheduleForm.listId != null || this.scheduleForm.listId != '') {
          if (this.scheduleForm.schedule == null) {
            this.scheduleForm.schedule = 0
          }

          this.$axios.put('/api/course/schedule', this.scheduleForm).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
            }
          })
        }
      }
    },
    // watch:{
    //   playerOptions:{
    //       sources:function(){
    //         this.load()
    //       },
    //       deep:true,
    //   }
    // },
    computed: {
      player() {
        return this.$refs.videoPlayer.player
      },
      // $route() {
      //   this.$destroy('videoPlayer')
      // }
    },
    mounted() {
      // this.timer = setInterval(this.saveVideoSchedule, 15000)

      // clearInterval(this.timer)
      let _this = this
      document.addEventListener('visibilitychange', function () {
        if (document.visibilityState == 'visible') {
          // alert('欢迎回来')
          console.log('欢迎回来')
          //do something
          //继续视频播放s
        }
        if (document.visibilityState == 'hidden') {
          _this.$refs.videoPlayer.player.pause()

          console.log('不要走！')
          //do something else
          //暂停视频播放
        }
      })
    },
    beforeDestroy() {
      clearInterval(this.timer)
    }
  }

</script>
<style>
  .vjs-progress-control {
    pointer-events: none !important;
  }

</style>
